package com.gxa.community.admin.controller.order;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gxa.community.admin.service.order.WayBillService;
import com.gxa.community.core.pojo.bo.order.WayBillAndOrderNo;
import com.gxa.community.core.pojo.vo.order.WayBillVo;
import com.gxa.community.core.utils.LittleUtils;
import com.gxa.community.core.utils.R;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class WayBillController {
    final WayBillService wayBillService;

    public WayBillController(WayBillService wayBillService) {
        this.wayBillService = wayBillService;
    }

    /**
     * 创建运货单
     */
    @PostMapping("/createWaybill")
    public R createWaybill(@RequestBody WayBillAndOrderNo wayBillAndOrderNo) {
        // 数据校验
        if (wayBillAndOrderNo.getOrders() == null || wayBillAndOrderNo.getOrders().isEmpty())
            return R.error("订单编号不能为空");
        //if (wayBillAndOrderNo.getWaybill() == null || wayBillAndOrderNo.getWaybill().getDriverId() == null
        //        || wayBillAndOrderNo.getWaybill().getDriverId() < 0)
        //    return R.error("司机ID不能为空");

        return wayBillService.createWaybill(wayBillAndOrderNo);
    }

    /**
     * 编辑运货单
     */
    @PutMapping("/editWaybill")
    public R editWaybill(@RequestBody WayBillAndOrderNo wayBillAndOrderNo) {
        // 数据校验
        if (wayBillAndOrderNo.getWaybill() == null || StringUtils.isBlank(wayBillAndOrderNo.getWaybill().getNo()))
            return R.error("运单号不能为空");

        if ((wayBillAndOrderNo.getOrders() == null || wayBillAndOrderNo.getOrders().isEmpty())
                && (wayBillAndOrderNo.getWaybill().getDriverId() == null || wayBillAndOrderNo.getWaybill().getDriverId() < 0)
                && StringUtils.isBlank(wayBillAndOrderNo.getWaybill().getTips())
        ) return R.error("待修改信息不能为空");

        return wayBillService.editWaybill(wayBillAndOrderNo);
    }

    /**
     * 确定发货
     */
    @PutMapping("/confirmShipment")
    public R confirmShipment(@RequestBody List<String> waybills) {
        return wayBillService.confirmShipment(waybills);
    }

    /**
     * 查询运货单
     */
    @PostMapping("/queryWaybill")
    public R queryWaybill(Integer page, Integer size, @RequestBody WayBillVo wayBillVo) {
        // 数据校验
        if (page == null || page < 1) page = 1;
        if (size == null || size < 1 || size > 100) size = 5;

        if (LittleUtils.checkNum(wayBillVo.getStatus(), 1, 4)) return R.error("运单状态有误");

        int i = LittleUtils.checkStartEndTime(wayBillVo.getStartTime(), wayBillVo.getEndTime());
        if (i == 1)
            return R.error("起始时间不能大于结束时间");
        else if (i == 2)
            return R.error("时间范围不允许超过两个月");

        return wayBillService.queryWaybill(page, size, wayBillVo);
    }
}
